<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="只允许第三级菜单被选中"
        :closable="false"
        type="warning"
        show-icon
      >
      </el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span>商品列表分类:</span>
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="optionsCate"
            @change="handleChange"
            clearable
          >
          </el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTagClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtnDisable"
            @click="addParamsVisiable = true"
            >添加参数</el-button
          >
          <el-table :data="manyTableList" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="closeItem(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParams(scope.row.attr_id)"
                  >修改</el-button
                >
                <!-- 删除 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isBtnDisable"
            @click="addParamsVisiable = true"
            >添加属性</el-button
          >
          <el-table :data="onlyTableList" border stripe>
            <el-table-column type="expand">
                 <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="closeItem(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParams(scope.row.attr_id)"
                  >修改</el-button
                >
                <!-- 删除 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 增加模态框 -->
      <el-dialog
        :title="'添加' + titleText"
        :visible.sync="addParamsVisiable"
        width="40%"
        @close="addParamsClose"
      >
        <el-form
          :model="addParamsForm"
          :rules="addParamsRules"
          ref="addParamsRef"
          label-width="80px"
        >
          <el-form-item label="参数名称" prop="attr_name">
            <el-input v-model="addParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addParamsVisiable = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改模态框 -->
      <el-dialog
        :title="'修改' + titleText"
        :visible.sync="editParamsVisiable"
        width="40%"
        @close="editParamsClose"
      >
        <el-form
          :model="editParamsForm"
          :rules="editParamsRules"
          ref="editParamsRef"
          label-width="80px"
        >
          <el-form-item label="参数名称" prop="attr_name">
            <el-input v-model="editParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editParamsVisiable = false">取 消</el-button>
          <el-button type="primary" @click="editParamsResults">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [], // 级联选择框数据
      selectedKeys: [], // 级联选择框选中的数组
      optionsCate: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
      },
      activeName: 'many', // 标签默认页
      onlyTableList: [], // 动态属性信息
      manyTableList: [], // 动态属性信息
      addParamsVisiable: false,
      editParamsVisiable: false,
      addParamsForm: {
        attr_name: '',
      },
      editParamsForm: {
        attr_name: '',
      },
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      editParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.getCateAllList()
  },
  methods: {
    // 获取级联选择框的数据
    async getCateAllList() {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类列表失败！')
      }
      this.cateList = res.data
    },
    // 级联选择框 选中的回调函数
    handleChange() {
      this.getParamsInfo()
    },
    // 标签选中
    handleTagClick() {
      this.getParamsInfo()
    },
    // 抽离获取属性的方法a
    async getParamsInfo() {
      if (this.selectedKeys.length !== 3) {
        this.onlyTableList = []
        this.manyTableList = []
        this.selectedKeys = []
        return
      }
      const { data: res } = await this.$http.get(
        `/categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取信息失败！')
      }
      res.data.forEach((element) => {
        element.attr_vals = element.attr_vals
          ? element.attr_vals.split(',')
          : []
        ;(element.inputVisible = false), (element.inputValue = '')
      })
      if (this.activeName == 'only') {
        this.onlyTableList = res.data
        console.log(this.onlyTableList)
      } else {
        this.manyTableList = res.data
        console.log(this.manyTableList)
      }
    },
    // 修改属性
    async editParams(id) {
      let { data: res } = await this.$http.get(
        `/categories/${this.cateId}/attributes/${id}`,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败！')
      }
      this.$message.error('获取成功！')
      this.editParamsForm = res.data
      this.editParamsVisiable = true
    },
    // 删除属性
    async deleteParams(id) {
      let resultConfirm = await this.$confirm(
        '此操作将永久删除该分类, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (resultConfirm != 'confirm') {
        return this.$message.warning('取消删除')
      }
      let { data: res } = await this.$http.delete(
        `/categories/${this.cateId}/attributes/${id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败！')
      }
      this.$message.success('删除该分类成功！')
      this.getParamsInfo()
    },
    // 添加模态框关闭事件
    addParamsClose() {
      console.log('123123')
      this.$refs.addParamsRef.resetFields()
    },
    editParamsResults() {
      this.editParamsVisiable = false
    },
    editParamsClose() {
      this.$refs.editParamsRef.resetFields()
    },
    // 添加模态框确定事件
    addParams() {
      this.$refs.addParamsRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `/categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败！')
        }
        this.$message.success('添加参数成功')
        this.getParamsInfo()
        this.addParamsVisiable = false
      })
    },
    // 标签的添加
    showInput(row) {
      row.inputVisible = true
      // $nextTick 当页面元素重新被渲染之后，才会指定回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false

      // 持久化数据，发起请求
      const { data: res } = await this.$http.put(
        `/categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(','),
        }
      )
      if (res.meta.status !== 201) {
        return this.$message.error('添加参数失败！')
      }
      this.$message.success('创建参数成功')
    },
    async closeItem(index, row) {
      row.attr_vals.splice(index, 1)
      // 持久化数据，发起请求
      const { data: res } = await this.$http.put(
        `/categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(','),
        }
      )
      if (res.meta.status !== 201) {
        return this.$message.error('删除参数失败！')
      }
      this.$message.success('删除参数成功')
    },
  },
  computed: {
    // 定义一个计算属性 判断button按钮是否警用
    isBtnDisable() {
      if (this.selectedKeys.length == 3) {
        return false
      }
      return true
    },
    // 获取最后一个id
    cateId() {
      if (this.selectedKeys.length == 3) {
        return this.selectedKeys[this.selectedKeys.length - 1]
      }
      return null
    },
    titleText() {
      if (this.activeName == 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
  },
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 10px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>